package control;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Vector;

import model.AnhaengerTyp;

public class ControlAnhangertypSuchen
{
	DatabaseAbfragen database;
	ResultSet rs = null;
	private final static int port = 0xCafe;
	private Socket socketToHost = null;
	private ObjectOutputStream os = null;
	private ObjectInputStream in = null;

	public ControlAnhangertypSuchen()
	{

	}

	public void closeAll()
	{
		try
		{
			if (os != null)
			{
				os.close();
			}

			if (in != null)
			{
				in.close();
			}

			if (socketToHost != null)
			{
				socketToHost.close();
			}
		} catch (IOException e)
		{
			System.out.println(e);
		}

		socketToHost = null;
		os = null;
		in = null;
	}

	boolean connectToHost()
	{
		if (socketToHost != null)
		{
			return true;
		}

		try
		{
			String host = InetAddress.getByName(DatabaseConnect.standardIP).getHostName();

			socketToHost = new Socket(host, port);

			os = new ObjectOutputStream(socketToHost.getOutputStream());
			in = new ObjectInputStream(socketToHost.getInputStream());

			return true;
		} catch (UnknownHostException e)
		{
			System.err.println(e);
		} catch (IOException e)
		{
			System.err.println(e);
		}catch (Exception e)
		{
			System.err.println(e);
		}

		closeAll();

		return false;
	}

	public Vector<AnhaengerTyp> getAnhaengertypen()
	{

		Vector<AnhaengerTyp> anhaengertyp = new Vector<AnhaengerTyp>();
		String statement = new String("sSELECT AnhaengerTypNummer, TypBezeichnung FROM anhaengertyp order by TypBezeichnung asc");
		if( !connectToHost(  ) ) {
            return anhaengertyp;
        }
		try {
			os.writeObject(statement);
			os.flush();
			rs = (ResultSet) in.readObject();
                        
        } catch( IOException | ClassNotFoundException e ) {
            System.err.println( e );
        }finally
        {
        	closeAll();
        }
		
		database = new DatabaseAbfragen();
		
		if (rs != null)
		{

			try
			{
				rs.beforeFirst();
				while (rs.next())
				{
					anhaengertyp.add(new AnhaengerTyp(rs
							.getInt("AnhaengerTypNummer"), rs
							.getString("TypBezeichnung")));
				}
			} catch (SQLException e)
			{
				e.printStackTrace();

			}
		}

		return anhaengertyp;
	}
}
